package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"mygame/app/utils"
	"mygame/config"
	"net/http"
)

type Weixin struct {
	AppID     string
	AppSecret string
}

var wxConfig Weixin

func init() {
	wxConfig = Weixin{AppID: config.App.Weixin.AppID, AppSecret: config.App.Weixin.AppSecret}
}

func (w Weixin) GetOpenid(code string) (openid string, err error) {
	ret, err := http.Get(fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", wxConfig.AppID, wxConfig.AppSecret, code))
	if err != nil {
		utils.Println("请求失败:", err)
		return "", err
	}
	defer ret.Body.Close()
	body, err := io.ReadAll(ret.Body)
	if err != nil {
		utils.Println("读取响应失败:", err)
		return "", err
	}
	var data map[string]interface{}
	err = json.Unmarshal(body, &data)
	if err != nil {
		utils.Println("解析 JSON 失败:", err)
		return "", err
	}
	utils.Println("响应数据:", data)
	if data["openid"] == nil {
		utils.Println("获取失败:", string(body))
		return "", errors.New(string(body))
	}
	return data["openid"].(string), nil
}
